﻿using System;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Models;

namespace Xoohoo.Modules.Membership.ModelBinders
{
    public class UserSearchCriteriaModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;

            Guid? userGroupID = null;
            UserStatus? status = null;
            string keyword = null;

            string strUserGroupID = null;
            string strStatus = null;

            keyword = valueProvider.GetAttemptedValue("keyword");
            strUserGroupID = valueProvider.GetAttemptedValue("userGroupID");
            strStatus = valueProvider.GetAttemptedValue("status");

            if (!String.IsNullOrEmpty(strUserGroupID))
            {
                Guid tmpUserGroupID;
                if (strUserGroupID.GuidTryParse(out tmpUserGroupID))
                {
                    userGroupID = tmpUserGroupID;
                }
            }
            if (!String.IsNullOrEmpty(strStatus))
            {
                //区分大小写
                if (Enum.IsDefined(typeof(UserStatus), strStatus))
                {
                    status = (UserStatus)Enum.Parse(typeof(UserStatus), strStatus);
                }
                //不区分大小写
                //try{status = (UserStatus)Enum.Parse(typeof(UserStatus), strStatus, true);}catch{}
            }
            return new UserSearchCriteria(userGroupID, status, keyword);
        }
    }
}
